package com.songlanyun.modules.studyingType.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.modules.studying.entity.Studying;
import com.songlanyun.modules.studying.service.StudyingService;
import com.songlanyun.modules.studyingType.dao.StudyingTypeDao;
import com.songlanyun.modules.studyingType.entity.StudyingType;
import com.songlanyun.modules.studyingType.service.StudyingTypeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service("studyingTypeService")
public class StudyingTypeServiceImpl extends ServiceImpl<StudyingTypeDao, StudyingType> implements StudyingTypeService {

    @Autowired
    private StudyingService studyingService;

    @Override
    public List<StudyingType> getAllStudy() {
        List<StudyingType> studyingTypes = this.baseMapper.selectList(new LambdaQueryWrapper<>());
        //把子类放入自己里面
        studyingTypes.forEach(studying -> studying.setStudyingTypes(studyingTypes.stream().filter(item -> item.getParentId().equals(studying.getId()))
                .sorted(Comparator.comparing(StudyingType::getHasOrder).thenComparing(StudyingType::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList())));
        //只返回父类id是顶层的级别 parentid=0
        return studyingTypes.stream().filter(item -> item.getParentId() == 0).sorted(Comparator.comparing(StudyingType::getHasOrder).thenComparing(StudyingType::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList());
    }

    @Override
    public StudyingType add(StudyingType studyingType) {
        if (ObjectUtil.isNotEmpty(studyingType.getParentId()) && studyingType.getParentId() != 0) {
            //看父类存不存在
            StudyingType parentStudy = this.loadById(studyingType.getParentId(), false);
            if (ObjectUtil.isNull(parentStudy)) {
                throw new RRException("父类不合法,请重新选择父级");
            }
            //树枝所在位置
            if (StringUtils.isEmpty(parentStudy.getParentPatten())) {
                studyingType.setParentPatten(parentStudy.getId().toString());
            } else {
                studyingType.setParentPatten(parentStudy.getParentPatten() + "," + parentStudy.getId());
            }
        }
        loadByName(studyingType);
        this.baseMapper.insert(studyingType);
        return studyingType;
    }

    @Override
    public StudyingType update(StudyingType studyingType) {
        loadByName(studyingType);
        //目前只允许修改名称和排序，怕人用工具乱搞，树形结构乱了
        StudyingType load = loadById(studyingType.getId(), true);
        load.setHasOrder(studyingType.getHasOrder());
        load.setStudyTypeName(studyingType.getStudyTypeName());
        this.baseMapper.updateById(load);
        return load;
    }

    //看名字有没有重复
    private void loadByName(StudyingType studyingType) {
        Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<StudyingType>()
                .eq(StudyingType::getParentId, studyingType.getParentId())
                .eq(StudyingType::getStudyTypeName, studyingType.getStudyTypeName())
                .ne(ObjectUtil.isNotNull(studyingType.getId()), StudyingType::getId, studyingType.getId()));
        if (integer > 0) {
            throw new RRException("同级别名称不能重复");
        }
    }

    @Override
    public StudyingType loadById(Long id, boolean b) {
        StudyingType studyingType = this.baseMapper.selectById(id);
        if (ObjectUtil.isNull(studyingType) && b) {
            throw new RRException("未找到该学习分类");
        }
        return studyingType;
    }


    @Override
    public void delete(Integer id) {
        //下面有分支不让删除
        Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<StudyingType>()
                .eq(StudyingType::getParentId, id));
        if (integer > 0) {
            throw new RRException("该分类有子分类，请先删除子分类");
        }
        // 分类被学习引用，也不让删除（上架状态和没有被标记删除）
        int count = studyingService.count(new LambdaQueryWrapper<Studying>()
                .eq(Studying::getStudyType, id)
                .eq(Studying::getHasDelete, false)
                .eq(Studying::getHasStatus, true));
        if (count > 0) {
            throw new RRException("删除失败,该分类下面有课程");
        }
        this.baseMapper.deleteById(id);
    }

    @Override
    public List<StudyingType> loadByParentId(Long parentId) {
        return this.lambdaQuery()
                .eq(StudyingType::getParentId, parentId)
                .orderByAsc(StudyingType::getHasOrder)
                .orderByDesc(StudyingType::getCreateTime)
                .list();
    }
}
